package cn.lovecyy.mockjson.core.type;

import cn.hutool.core.util.StrUtil;

import cn.lovecyy.mockjson.core.context.ContextGenerator;
import cn.lovecyy.mockjson.core.context.ContextGeneratorRegistry;
import cn.lovecyy.mockjson.core.domain.TypeConfig;
import cn.lovecyy.mockjson.core.gen.DateGenContainer;

import java.util.HashMap;
import java.util.Map;

/**
 * CtxTypeMocker
 *
 * @author Yakir
 */
public class CtxTypeMocker implements TypeMocker {

	@Override
	public String getType() {
		return "ctx";
	}

	@Override
	public Object mock(TypeConfig config) {
		// ctx
		String type = config.getType();
		// name|p1.name
		String param = config.getParam();
		String format = config.getFormat();
		Map<String, Object> context = config.getContext();
		String ctxKey;
		String innerKey;
		if (param.contains(".")) {
			ctxKey = type + "." + format + "." + StrUtil.sub(param, 0, param.lastIndexOf("."));
			innerKey = StrUtil.sub(param, param.lastIndexOf(".") + 1, param.length());
		}
		else {
			// ctx.name
			ctxKey = type + "." + format;
			innerKey = param;
		}

		Map<String, Object> userCtx = (Map<String, Object>) context.computeIfAbsent(ctxKey, k -> getCtxInfo(config));
		return userCtx.get(innerKey);
	}

	public Map<String, Object> getCtxInfo(TypeConfig config) {
		ContextGenerator contextGenerator = ContextGeneratorRegistry.get(config.format);
		if (contextGenerator == null) {
			return config.getContext();
		}
		return contextGenerator.generate(config);
		// if ("person".equals(format)){
		// return DateGenContainer.getDataGen().personInfo();
		// }
		// if ("bank".equals(format)){
		// return BankCardMockUtil.randomBankCardInfo();
		// }
		// return new HashMap<>();
	}

}
